package com.market.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {
    private static String signature="market";
    public static String getToken(Integer id, long expireTime,String role) {
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("type","JWT")
                .setHeaderParam("alg","HS256")
                .setId(id.toString())
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .claim("role",role)
                .signWith(SignatureAlgorithm.HS256,signature);
        String token = builder.compact();
        return token;
    }

    public static Map<String,Object> parseToken(String token){
        Map<String,Object> map = new HashMap<>();
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws=parser.setSigningKey(signature).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        map.put("id",body.getId());
        map.put("role",body.get("role"));
        map.put("expireTime",body.getExpiration());
        return map;
    }

    public static void main(String[] args) {
        String token = getToken(1, 1000 * 5,"asf");
        Map<String, Object> map = parseToken(token);
        System.out.println(map.get("id"));
        System.out.println(map.get("role"));
    }
}
